package com.sx.service.system;

import com.sx.basic.ResponseEntity;
import com.sx.basic.TokenEntity;
import com.sx.basic.TokenService;
import com.sx.basic.enums.HttpMethod;
import com.sx.basic.exception.BasicException;
import com.sx.basic.service.BasicService;
import com.sx.basic.service.impl.BasicServiceImpl;
import com.sx.dao.system.AdminRepository;
import com.sx.dto.AdminInfo;
import com.sx.entity.system.AdminEntity;
import com.sx.entity.system.MenuEntity;
import com.sx.entity.system.RoleEntity;
import com.sx.utils.DateUtils;
import com.sx.utils.PasswordUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author AdinZ
 * @date 2020/11/10 18:14
 */
@Service
public class AdminService extends BasicServiceImpl<AdminRepository, AdminEntity,Long>
        implements BasicService<AdminEntity,Long>, IAdminService {
    @Resource private TokenService tokenService;
    @Resource private RoleService roleService;
    @Resource private MenuService menuService;

    /**
     * 管理员登陆
     * @param username 账号
     * @param password 密码
     * @return data 返回token
     */
    @Override
    public ResponseEntity<String> login(String username, String password) {
        if(StringUtils.isEmpty(username))return new ResponseEntity().toError("账号不能空");
        if(StringUtils.isEmpty(password))return toError("密码不能空");
        AdminEntity entity = this.repository.getByUsername(username);
        if(entity==null)return toError("用户不存在");
        if(!StringUtils.equals(entity.getPassword(), PasswordUtils.getInstance().md5(password)))
            return toError("密码错误");
        TokenEntity tokenEntity=new TokenEntity(entity.getId(), TokenEntity.Type.SYSTEM, TokenEntity.Channel.PC,entity, DateUtils.addHour(1).getTime());
        this.tokenService.tokenGen(tokenEntity);
        return toSuccess("登陆成功",tokenEntity.getToken());
    }

    @Override
    public ResponseEntity logout(String token) {
        if(StringUtils.isEmpty(token))
            return toError();
        this.tokenService.deleteToken(token);
        return toSuccess();
    }

    @Override
    public ResponseEntity<AdminInfo> getInfo(String token) {
        long uid = this.tokenService.getUid(token);
        AdminEntity adminEntity = this.get(uid);
        if (adminEntity == null) return toError("管理员不存在或被禁用");
        RoleEntity roleEntity = this.roleService.get(adminEntity.getRoleId());
        if (roleEntity == null) return toError("还未分配角色权限");
//        List<MenuEntity> menuEntities = this.menuService.listById(roleEntity.getMenuIds());
//        List<Long> list = menuEntities.stream().filter(e -> e.getAction() == MenuEntity.Action.UI).map(MenuEntity::getId).collect(Collectors.toList());
        AdminInfo adminInfo = new AdminInfo();
        BeanUtils.copyProperties(adminEntity, adminInfo);
        adminInfo.setRoleName(roleEntity.getRoleName());
        adminInfo.setMenus(roleEntity.getMenuIds());
        return toSuccess(adminInfo);
    }

    @Override
    public ResponseEntity putAdmin(AdminEntity entity) {
        return null;
    }

    @Override
    public ResponseEntity deleteAdmin(Long[] ids) {
        return null;
    }

    @Override
    public boolean isAuthority(String token, String method, String requestURI) {
        TokenEntity<AdminEntity> tokenEntity = this.tokenService.getToken(token);
        if(tokenEntity.getData().getRoleId()==0)return true;
        //角色实体
        RoleEntity roleEntity = this.roleService.get(tokenEntity.getData().getRoleId());
        if (roleEntity == null) throw new BasicException(ResponseEntity.CODE_AUTHOR_FAIL, "管理员还未分配角色权限");
        //全部的角色菜单id
        List<Long> menuIds = roleEntity.getMenuIds();
        //菜单列表
        List<MenuEntity> list = this.menuService.findMenu(MenuEntity.Action.API);
        if (list == null || list.size() == 0) throw new BasicException(ResponseEntity.CODE_AUTHOR_FAIL, "角色没有任何权限");
        for (MenuEntity menu : list) {
            if (!menuIds.contains(menu.getId())) continue;
            //正则匹配url是否有权限
            if (Pattern.matches(menu.getUrl(), requestURI)&&menu.getMethod() == HttpMethod.valueOf(method)) {
                return true;
            }
        }
        throw new BasicException(ResponseEntity.CODE_AUTHOR_FAIL, "权限不足");
    }


    /**
     * 变更用户密码
     * @param token
     * @param oldPassword
     * @param password
     * @return
     */
    @Override @Transactional
    public ResponseEntity updatePwd(String token, String oldPassword, String password) {
        long uid=this.tokenService.getUid(token);
        this.updatePwd(uid,oldPassword,password);
        return toSuccess();
    }

    @Override @Transactional
    public boolean updatePwd(long uid, String oldPassword, String password) {
        AdminEntity entity = get(uid);
        if (entity == null) throw new BasicException("账号不存在");
        if (!StringUtils.equals(entity.getPassword(), PasswordUtils.getInstance().md5(oldPassword)))
            throw new BasicException("密码错误");
        entity.setPassword(PasswordUtils.getInstance().md5(password));
        super.update(entity);
        return true;
    }
}
